package com.csdj.t309springboot.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csdj.t309springboot.common.WebResult;
import com.csdj.t309springboot.common.WebResultMsgCode;
import com.csdj.t309springboot.entity.User;
import com.csdj.t309springboot.service.IUserService;
import com.csdj.t309springboot.utils.SignurateUtil;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.TreeMap;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author cloud
 * @since 2021-12-30
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Resource
    private IUserService userService;

    @PostMapping("/login")
    public WebResult login(@RequestParam String username, @RequestParam String password){
        User user = userService.login(username, password);
        if(user != null){
            return new WebResult(WebResultMsgCode.SUCCESS,user);
        }
        return new WebResult(WebResultMsgCode.USER_PWD_ERROR);
    }

    @GetMapping("/all")
    public WebResult getAllUser(@RequestParam(value = "page",defaultValue = "1") int curPage,
                                @RequestParam(value = "rows",defaultValue = "12") int rows){
        IPage<User> page = new Page<>();
        page.setSize(rows);
        page.setPages(curPage);
        page = userService.page(page);
        return new WebResult(WebResultMsgCode.SUCCESS,page.getRecords()).putData("total",page.getTotal());
    }

    @GetMapping("/gen")
    public WebResult addUsers(@RequestParam int num){
        userService.addUsersByRandom(num);
        return new WebResult(WebResultMsgCode.SUCCESS);
    }


    @PostMapping("/update")
    public WebResult update(){
        User user = new User();
        user.setId(3);
        user.setTopId(100);
        userService.update(user);
        return new WebResult(WebResultMsgCode.SUCCESS);
    }

    /**
     * 第三方登錄回調接口
     * @return
     */
    @PostMapping("/callback")
    public WebResult callback(@RequestParam("username")String username,
                              @RequestParam("email")String email,
                              @RequestParam("nickname")String nickname,
                              @RequestParam("desc")String desc,
                              @RequestParam("accessKey")String accessKey,
                              @RequestParam("sign")String sign){
        TreeMap<String,String> map = new TreeMap<>();
        map.put("username",username);
        map.put("email",email);
        map.put("nickname",nickname);
        map.put("desc",desc);
        map.put("accessKey",accessKey);
        if(!SignurateUtil.checkSign(map,sign)){
            return new WebResult(WebResultMsgCode.FAIL);
        }
        return new WebResult(WebResultMsgCode.SUCCESS);


    }



}
